﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Reflection;
using System.IO;
using System.Text;

namespace Noria.Net.Chaos.Net
{
    [TestClass]
    public class TamperRuleTest
    {
        [TestMethod]
        public void Normal()
        {
            var tin = LoadPayload("in");
            var tout = LoadPayload("out");
            var rule = new TamperRule(LoadPayloadAsText("match"), LoadPayloadAsText("replacement"));

            var buffer = new byte[(int)(tin.Length * 1.3)];
            Array.Copy(tin, 0, buffer, 0, tin.Length);

            var length = tin.Length;
            bool rc = rule.Apply(buffer, ref length);

            Assert.IsTrue(rc);
            Assert.AreEqual(2, length - tin.Length, "Output buffer should be 2 bytes great than input one");
            Assert.AreEqual(tout.Length, length, "Output buffer (length) should equal to predefined out.txt");
            Assert.AreEqual(0, TamperRule.IndexOf(buffer, tout), "Output buffer (content) should equal to predefined out.txt");
        }

        private string LoadPayloadAsText(string name)
        {
            var res = String.Format("{0}.{1}.txt", GetType().FullName, name);
            var s = Assembly.GetExecutingAssembly().GetManifestResourceStream(res);
            using (BinaryReader br = new BinaryReader(s))
            {
                var raw = br.ReadBytes((int)s.Length);
                return Encoding.ASCII.GetString(raw, 3, raw.Length - 3);
            }
        }

        private byte[] LoadPayload(string name)
        {
            return TamperRule.MakeByteArray(LoadPayloadAsText(name));
        }
    }
}
